package com.dmall.graph.bfs;

import com.dmall.graph.Graph;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author: xiao1.wang
 * @date: 2022/6/19 16:13
 */
public class CycleDetection1 {
    private Graph G;
    private int[] pre;
    private boolean hasCycle;

    public CycleDetection1(Graph G) {
        this.G = G;
        this.pre = new int[G.V()];
        Arrays.fill(this.pre, -1);
        for (int i = 0; i < G.V(); i++) {
            if (pre[i] == -1) {
                if (bfs(i)) {
                    hasCycle = true;
                    break;
                }
            }
        }
    }

    private boolean bfs(int v) {
        pre[v] = v;
        Queue<Integer> queue = new LinkedList<>();
        queue.add(v);
        while (!queue.isEmpty()) {
            Integer cur = queue.remove();
            for (Integer w : G.adj(cur)) {
                if (pre[w] == -1) {
                    // 未访问过w节点
                    pre[w] = cur;
                    queue.add(w);
                } else {
                    // 访问过w节点
                    if (w != pre[cur]) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public boolean hasCycle() {
        return hasCycle;
    }

    public static void main(String[] args) {
        String filename = CycleDetection1.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        CycleDetection1 cycleDetection = new CycleDetection1(g);
        System.out.println(cycleDetection.hasCycle());

        String filename2 = CycleDetection1.class.getClassLoader().getResource("g2.txt").getPath();
        Graph g2 = new Graph(filename2);
        CycleDetection1 cycleDetection2 = new CycleDetection1(g2);
        System.out.println(cycleDetection2.hasCycle());
    }
}
